package com.example.idea.service;

import com.example.idea.entity.News;
import com.example.idea.entity.User;
import com.example.idea.mapper.NewsMapper;
import com.example.idea.utils.Page;
import com.example.idea.utils.TokenUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NewsService {

    @Resource
    private NewsMapper newsMapper;

    public void add(News news) {
//        获取当前系统时间（yyyy-MM-dd HH:mm:ss）
        news.setTime(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()));
        User currentUser = TokenUtils.getCurrentUser();
        news.setAuthorid(currentUser != null ? currentUser.getId() : 0); // 0 或其他默认值
        newsMapper.add(news);
    }

    public void update(News news) {
        newsMapper.update(news);
    }

    public void delete(Integer id) {
        newsMapper.delete(id);
    }

    public User query(Integer id) {
        return newsMapper.query(id);
    }

    public void deleteBatch(List<Integer> ids) {
//        将获取到的ids转化成（12，25）格式
        String idsStr = ids.toString().replace("[", "").replace("]", "");
        newsMapper.deleteBatch(idsStr);
    }

    public List<News> list() {
        return newsMapper.list();
    }

    public List<News> selectList(News news) {
        return newsMapper.selectList(news);
    }

    public Page<News> selectByPage(Integer pageNum, Integer pageSize, String title, String description) {
        Integer skipNum = (pageNum - 1) * pageSize;
        Page<News> page = new Page<>();
        List<News> newsList = newsMapper.selectByPage(skipNum, pageSize, title, description);
        Integer total = newsMapper.selectCountByPage(title, description);
        page.setList(newsList);
        page.setTotal(total);
        return page;
    }
}
